<?php
require_once 'pages/TMSCollectionItemPage.inc';

class TMSCollectionCreatePage extends TMSCollectionItemPage {
	protected $creationClass = null;
	
	protected function getItem(){
		$dummy = $this->Model->GetDummyItem(null,$this->creationClass);
		$n = $this->FilterProperty;
		$dummy->$n = $this->request->container;
		return new TMSPageItem($dummy,$this);
	}
	
	public function Handle(THttpRequest $request){
		if (count($this->Model->AssumedDescendants) == 0)
			$this->creationClass = $this->Model->ClassName();
		else if ($request->itemtype)
			$this->creationClass = $request->itemtype;
		return parent::Handle($request);
	}
	
	public function http_SelectCreationType($type){
		$this->creationClass = $type;
	}	
	
	protected function processUrlParameters(array $parameters){
		$parameters['itemtype'] = $this->creationClass;
		return parent::processUrlParameters($parameters);
	}
	
	public function NeedSelectClass(){
		return is_null($this->creationClass);
	}
	
	public function ClassSelection(){
		$result = array();
		foreach ($this->Model->ExplicitDescendants as $class){
			$c = false;
			if ($this->Service()->MetaSettings)
				$c = $this->Service()->MetaSettings->GetValue($class.'.Caption');
			if ($c)
				$result[$class] = $c;
			else
				$result[$class] = $class;
		}
		return $result;
	}
	
	protected function doCreate($data){
		$data[$this->FilterProperty] = $this->request->container;
		return $this->Model->CreateItem($data,$this->creationClass);
	}
	
	protected function doSave($data){
		$item = $this->doCreate($data);
		if ($item)
			$this->Application()->Redirect($this->service->Url($this->listPath(),null,null,array("id"=>$item->ItemId(),"container"=>$this->request->container)));
	}
	
}